package games.isoMatric
{
	import as3isolib.core.IsoContainer;
	import as3isolib.core.IsoDisplayObject;
	import as3isolib.data.Node;
	import as3isolib.display.IsoSprite;
	import as3isolib.display.IsoView;
	import as3isolib.display.primitive.IsoBox;
	import as3isolib.display.scene.IsoGrid;
	import as3isolib.display.scene.IsoScene;
	import as3isolib.geom.IsoMath;
	import as3isolib.geom.Pt;
	
	import core.Global;
	
	import eDpLib.events.ProxyEvent;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.utils.getTimer;
	
	import games.cube.Cube;
	import games.cube.DragCube;
	import games.isoMatric.data.GameData;
	import games.isoMatric.data.Player;
	import games.isoMatric.ui.MarkOwerSprite;
	import games.isoMatric.ui.Role;
	
	import interfaces.IGame;
	
	import module.Atom;
	import module.aStar3D.AStar;
	import module.aStar3D.Grid;
	
	public class IsomatricTest implements IGame
	{
		private var m_data:GameData;		// 游戏数据
		private var m_playerInfo:Player;	// 人物信息
		
		// 寻路的数据
		private var m_gridAStar:Grid;		// 寻路栅格信息
		private var m_path:Array;
		private var m_index:int;
		private var m_time:Number = 0;
		private var m_speed:Number = .1;
		
		private var m_control:MovieClip;	// 控制界面
		
		// -----------------isomatric中各显示对象----------------
		private var m_view:IsoView;			// 显示区域
		private var m_scene:IsoScene;		// 绘制场景
		private var m_grid:IsoGrid;			// 栅格
		private var m_boxs:Vector.<IsoSprite>;
		private var m_player:IsoSprite;		// 人物形象
		// -----------------/isomatric中各显示对象----------------
		private var m_cube:Cube;
		
		public function IsomatricTest()
		{
		}
		
		public function start():void
		{
			initData();
			initUi();
			initControl();
		}
		
		 
		/**************************************控制设置*************************************/
		private function initControl():void
		{
			// 初始化控制
			m_control =  Atom(Global.loadResource(GFrame.MAIN_UI,"mcControl")).getChildAt(0) as MovieClip;
			Global.stage.addChild(m_control);
			m_control.addEventListener(MouseEvent.CLICK,onClickControl);
			
			// 游戏数据改变后，视图调整
			m_data.addEventListener(GameData.WIDTH_CHANGE,onViewChange);
			m_data.addEventListener(GameData.CELLSIZE_CHANGE,onCellChange);
			m_data.addEventListener(GameData.COLUMN_CHANGE,onClumnChange);
			m_data.addEventListener(GameData.ROW_CHANGE,onRowChange);
			m_data.addEventListener(GameData.BOXSNUM_CHNAGE,onBoxnumChange);
			
			m_view.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown); // 处理拖动视图
			m_view.addEventListener(MouseEvent.CLICK,onClickView);		// 鼠标点击栅格
		//	m_scene.addEventListener(MouseEvent.CLICK,onClickGrid);
		}
		
		protected function onBoxnumChange(event:Event):void
		{
			// TODO Auto-generated method stub
			randomAddBox(m_data.totalBoxs);
		}
		
		protected function onClickView(e:MouseEvent):void
		{
//			trace(e.target.parent.name,"///////",e.target,e.target.name);
			 
		 
			
//			if(getChildByPt(pt) is IsoBox)
//			{
//				addBox(Math.floor(pt.x / m_data.cellSize) * m_data.cellSize,Math.floor(pt.y / m_data.cellSize) * m_data.cellSize,(getChildByPt(pt).z + 1) * m_data.cellSize);
//			}
			trace(e.target);
			if(e.target is MarkOwerSprite)
			{
				var mc:MarkOwerSprite = e.target as MarkOwerSprite;
				var pt:Pt = new Pt(Math.floor(mc.owner.x / m_data.cellSize),Math.floor(mc.owner.y / m_data.cellSize),Math.floor(mc.owner.z / m_data.cellSize) + 1)
				if(m_data.editMode)
				{
					addBox(pt.x * m_data.cellSize,pt.y * m_data.cellSize,pt.z * m_data.cellSize);	
					return;
				}
			}else
			{
				var me:MouseEvent = MouseEvent(e);
				pt = new Pt(me.localX / m_data.cellSize,me.localY / m_data.cellSize);
				IsoMath.screenToIso(pt);
				if(m_data.editMode)
				{
					addBox(Math.floor(pt.x ) * m_data.cellSize,Math.floor(pt.y ) * m_data.cellSize,0);
					return;
				}
			}
			
			// 寻路
			var pto:Pt = new Pt(m_player.screenX,m_player.screenY,m_player.z);
			IsoMath.screenToIso(pto);
			m_gridAStar.setStartNode(Math.floor(pto.x / m_data.cellSize),Math.floor(pto.y / m_data.cellSize),0);
			//m_box.moveTo(pt.x,pt.y,0);
			
			var targetz:Number = Math.floor(Math.random() * 10);
			trace("target place: ",pt.x,pt.y,pt.z);
			m_gridAStar.setEndNode(pt.x,pt.y,pt.z);
			var astar:AStar = new AStar();
			if(astar.findPath(m_gridAStar))
			{
				m_path = astar.path;
				m_index = 0;
				Global.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
				m_playerInfo.state = Player.M_WALK;
			 
			}
//			for(var i:int = 0; i < m_scene.children.length; i++)
//			{
//				if(IsoDisplayObject(m_scene.children[i]).container.contains(DisplayObject(e.target)))
//				{
//					if(IsoDisplayObject(m_scene.children[i]) is IsoBox)
//					{
//						var pt:Pt = new Pt(Math.floor(IsoDisplayObject(m_scene.children[i]).x / m_data.cellSize),Math.floor(IsoDisplayObject(m_scene.children[i]).y / m_data.cellSize),Math.floor(IsoDisplayObject(m_scene.children[i]).z / m_data.cellSize) + 1)
//						trace(pt.x,pt.y,pt.z);
//					 	addBox(pt.x * m_data.cellSize,pt.y * m_data.cellSize,pt.z * m_data.cellSize);
//					}
//				}
//			}
		}
		
		protected function onClickGrid(event:ProxyEvent):void
		{
			
			var me:MouseEvent = MouseEvent(event.targetEvent);
			trace("*********",event.target,event.proxyTarget);
			var pt:Pt = new Pt(me.localX,me.localY);
		 
			IsoMath.screenToIso(pt);
			 
			if(m_data.editMode)
			{
				// 编辑状态
				var znum:int = 0;
				addBox(Math.floor(pt.x / m_data.cellSize) * m_data.cellSize,Math.floor(pt.y / m_data.cellSize) * m_data.cellSize,znum);
				return;
			}
		
		}
		
		 
		
		
		protected function onEnterFrame(event:Event):void
		{
			// TODO Auto-generated method stub
			
			m_time += m_speed;
			if(m_time >= 1)
			{
				m_index++;
			}
			if(m_index == m_path.length )
			{
				m_playerInfo.state = Player.M_STAND;
				// 视图移到人物位置
				//m_view.centerOnIso(m_player);
				
				return;
			}
			m_time %= 1;
			if(m_path[m_index + 1] == undefined)return;
			var x1:Number = Math.round(((m_path[m_index + 1].x - m_path[m_index ].x) * m_time +m_path[m_index ].x) * m_data.cellSize );
			var y1:Number =  Math.round(((m_path[m_index+ 1].y - m_path[m_index].y) * m_time + m_path[m_index ].y) * m_data.cellSize);
			var z1:Number =  Math.round(((m_path[m_index+ 1].z - m_path[m_index].z) * m_time + m_path[m_index ].z) * m_data.cellSize);
			m_player.moveTo( x1, y1 ,z1);
			
			changePlayerDirection();
			m_scene.render();
		}	
		
		private function changePlayerDirection():void
		{
			if(m_path[m_index + 1].x < m_path[m_index ].x)
			{
				if(m_path[m_index + 1].y < m_path[m_index].y)
				{
					m_playerInfo.direction = Player.DIR_NORTH;
				}else if(m_path[m_index + 1].y == m_path[m_index].y)
				{
					m_playerInfo.direction = Player.DIR_NORTHWEST;
				}else
				{
					m_playerInfo.direction = Player.DIR_WEST;
				}
				
			}else if(m_path[m_index + 1].x == m_path[m_index ].x)
			{
				if(m_path[m_index + 1].y < m_path[m_index].y)
				{
					m_playerInfo.direction = Player.DIR_NORTHEAST;
				}else if(m_path[m_index + 1].y == m_path[m_index].y)
				{
					//m_playerInfo.direction = 5;
				}else
				{
					m_playerInfo.direction = Player.DIR_SOUTHWEST;
				}
			}else
			{
				if(m_path[m_index + 1].y < m_path[m_index].y)
				{
					m_playerInfo.direction = Player.DIR_EAST;
				}else if(m_path[m_index + 1].y == m_path[m_index].y)
				{
					m_playerInfo.direction = Player.DIR_SOUTHEAST;
				}else
				{
					m_playerInfo.direction = Player.DIR_SOUTH;
				}	
			}
		}
		
		protected function onMouseDown(event:MouseEvent):void
		{
			trace(event.target);
			
			// 按下鼠标 视图界面触发监听
			m_view.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
			m_view.addEventListener(MouseEvent.MOUSE_UP,onMouseUp);
		}
		
		protected function onMouseUp(event:MouseEvent):void
		{
			// 松开鼠标停止拖动,并移除监听
			m_view.stopDrag();
			m_view.removeEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
			m_view.removeEventListener(MouseEvent.MOUSE_UP,onMouseUp);
			m_view.mouseChildren = true;
		}
		
		protected function onMouseMove(event:MouseEvent):void
		{
			// 鼠标移动开始拖动视图界面
			m_view.startDrag();
			m_view.mouseChildren = false;
		}
		
		protected function onRowChange(event:Event):void
		{
			// 栅格行数改变
			showGrid();
		}
		
		protected function onClumnChange(event:Event):void
		{
			// 栅格列改变
			showGrid();
		}
		
		protected function onCellChange(event:Event):void
		{
			// 单元格改变
			showGrid();
		}
		
		private function setGrid():void
		{
			// 设置格子数据
			m_data.cellSize = int( TextField(m_control.getChildByName("inputCell")).text);
			m_data.rows = int(TextField( m_control.getChildByName("inputX")).text);
			m_data.columns = int(TextField( m_control.getChildByName("inputY")).text);
			
	
			 
			
		}
		
		protected function onClickControl(event:Event):void
		{
			// 根据按钮名称触发
			var name:String = event.target.name;
			trace(name);
			switch(name)
			{
				case "btnSet":
					setGrid();
					break;
				case "btnUp":
					m_data.totalBoxs = int(TextField(m_control.getChildByName("inputBox")).text);
				
					break;
				case "btnDown":
					removeAllBoxs();
					break;
				case "btnAdd":
					m_data.editMode = !m_data.editMode;
					break;
			}
		}
		
		//**************************************/控制设置*************************************/
		
			
		//***************************************界面设置*************************************/
		private function initUi():void
		{
			var t1:Number = getTimer();
			// 初始化界面
			m_view = new IsoView();
			m_view.centerOnPt(new Pt(200,200,0));
			Global.stage.addChild(m_view);
			onViewChange();
			
			m_scene = new IsoScene();
			m_view.addScene(m_scene);
			
			m_grid = new IsoGrid();
			m_grid.setGridSize(m_data.rows,m_data.columns);
			m_grid.cellSize = m_data.cellSize;
			m_scene.addChild(m_grid);
			
			m_boxs = new Vector.<IsoSprite>();
//			m_box = new IsoBox();
//			m_box.setSize(m_data.cellSize,m_data.cellSize,m_data.cellSize);
//			m_scene.addChild(m_box);
//			m_box.moveTo(200,200,0);
			
			randomAddBox(15);
			
			m_player = new IsoSprite();
			m_player.sprites = [new MarkOwerSprite(m_player)];
			m_player.sprites[0].addChild(new Role(m_playerInfo));
			m_player.setSize(m_data.cellSize,m_data.cellSize,m_data.cellSize * 2);
			m_player.moveTo(100,100,0);
			//m_player.sprites.push(Global.loadResource(GFrame.MAIN_UI,"PubSHeadMale"));
			m_scene.addChild(m_player);
			
			var t:Number = getTimer();
			m_scene.render();
			trace("*************************",t1,t,getTimer());
		}
		
		protected function onViewChange(event:Event = null):void
		{
			// 视图界面设置尺寸
			m_view.setSize(m_data.width,m_data.height);
		}
		
		
		private function showGrid():void
		{
			// 栅格调整尺寸
			m_grid.setGridSize(m_data.rows,m_data.columns);
			m_grid.cellSize = m_data.cellSize;
			m_gridAStar = new Grid(m_data.rows,m_data.columns,0);
			m_scene.render();
		}
		
		
		private function addBox(x:Number,y:Number,z:Number = 0):void
		{
			// 添加一个isoBox
			
			 
			var sprite:IsoSprite  = new IsoSprite();
		
			
			sprite.moveTo(x,y,z);
			var moSprite:MarkOwerSprite = new MarkOwerSprite(sprite);
			moSprite.graphics.beginFill(0);
			moSprite.graphics.drawCircle(0,0,10);
			moSprite.graphics.endFill();
			var box:IsoBox = new IsoBox();
			sprite.sprites = sprite.sprites.concat(box.container);
			box.container.mouseChildren = false;
			box.container.mouseEnabled = false;
			box.setSize(m_data.cellSize,m_data.cellSize,m_data.cellSize);
			sprite.addChild(box);
			sprite.setSize(m_data.cellSize,m_data.cellSize,m_data.cellSize);
			
			if(x >= 0 && y >= 0 && z >= 0 && m_gridAStar.getNode(x / m_data.cellSize,y / m_data.cellSize,Math.floor(z / m_data.cellSize)).walkable)
			{
				m_gridAStar.setWalkable(x / m_data.cellSize,y / m_data.cellSize,Math.floor(z / m_data.cellSize),false);
				m_gridAStar.setWalkable(x / m_data.cellSize,y / m_data.cellSize,Math.floor(z / m_data.cellSize) + 1,true);
				m_scene.addChild(sprite);
				m_boxs.push(sprite);
				m_scene.render();
			}
			trace(x,y,z,x / m_data.cellSize,y / m_data.cellSize);
			
			
			
		
		}
		
		private function removeBox(box:IsoSprite):void
		{
			m_gridAStar.setWalkable(box.x / m_data.cellSize,box.y / m_data.cellSize,box.z / m_data.cellSize,true);
			m_scene.removeChild(box);
			m_boxs.splice(m_boxs.indexOf(box),1);
			m_scene.render();
		}
		
		private function removeAllBoxs():void
		{
			for(var i:int = 0; i < m_boxs.length; i++)
			{
				removeBox(m_boxs[i]);
				
				i--;
			}
			
		}
		
		private function randomAddBox(n:int):void
		{
			for(var i:int = 0; i < n; i++)
			{
				addBox(int(m_data.rows * Math.random()) * m_data.cellSize,int(m_data.columns * Math.random()) * m_data.cellSize);
			}
		}
		
		//***************************************/界面设置*************************************/
		
		//***************************************数据设置*************************************/
		private function initData():void
		{
			// 初始化数据
			m_data = new GameData();
			
			// 初始化人物信息
			m_playerInfo = new Player();
			// 初始化寻路栅格
			m_gridAStar = new Grid(m_data.rows,m_data.columns,20);
			for(var i:int = 0; i < m_gridAStar.numDepths; i++)
			{
				for(var j:int = 0; j < m_gridAStar.numCols;j++)
				{
					for(var k:int = 0; k < m_gridAStar.numRows; k++)
					{
						m_gridAStar.setWalkable(k,j,i,i==0)
					}
				}
			}
		}
		
		//***************************************/数据设置*************************************/
		
		public function destroy():void
		{
		}
		
		
	
		
	}
}